#181.fm Plugin
import sys,urllib,urllib2,urlparse,random
import xbmcgui, xbmcplugin, xbmcaddon
from BeautifulSoup import BeautifulSoup, SoupStrainer

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
try:
    from urlparse import parse_qs
except ImportError:
    #python 2.4 compatibility
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs
args = urlparse.parse_qs(sys.argv[2][1:])

#PLUGIN CONSTANTS
plugin_id = 'plugin.audio.181fm'
addon = xbmcaddon.Addon(id=plugin_id)
icon = addon.getAddonInfo('icon')

#COMMON PLUGIN FUNCTIONS
#subfolder url link
def build_url(query):
    return base_url + '?' + urllib.urlencode(query)

#chrome web browser act a like
useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'

def getURL(url):
        print '>>>>>181.fm Plugin :: getURL :: url = '+url
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', useragent)
            response = urllib2.urlopen(req)
            link=response.read()
            response.close()
        except urllib2.HTTPError, error:
            print 'Error reason: ', error
            return error.read()
        else:
            return link

mode = args.get('mode', None)
 
if mode is None:
    url = 'http://www.181.fm/player/'
    data = getURL(url)
    stations = SoupStrainer(id="stations-select-container")
    soup = BeautifulSoup(data, parseOnlyThese=stations)
    stationlist = soup.findAll('option')
    for station in stationlist:
        name = station.text
        value = station['value']
        url = build_url({'mode': 'streamlink', 'foldername': name, 'value': value})
        li = xbmcgui.ListItem(name, iconImage='DefaultAudio.png')
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'streamlink':
    stationtitle = args['foldername'][0]
    value = args['value'][0]
    url = 'http://www.181.fm/winamp.pls?station=' + value + '&file=' + value + '.pls'
    data = getURL(url)
    servers = [
        l.split('=')[1] for l in data.splitlines()
        if l.lower().startswith('file')
    ]
    serverstream = random.choice(servers)
    li = xbmcgui.ListItem('Stream Station', iconImage='DefaultAudio.png')
    li.setThumbnailImage(icon)
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=serverstream, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)
